﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FCModel;
using FCBLL;


namespace FileConverter.Bas
{
    public partial class StandardData : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                QueryByPartNo();
            }
        }

        private void BindData()
        {
            /* using (var ctx = new IQCDBEntities())
             {
            //将 System.Data.Objects.ObjectQuery<Categories> 绑定到 Gridview1
            //GridView1.DataKeyNames = new string[] { "specialtyid", "courseid" };
            GridView1.DataSource = ctx.ParameterRange.ToList(); ;
            GridView1.DataBind();
             }*/
            GridView1.DataSource = new BaseRepositoryBLL<ParameterRange>().LoadAllEntities().ToList<ParameterRange>();
            GridView1.DataBind();
        }

        /// <summary>
        /// 添加标准
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddStandard_Click(object sender, EventArgs e)
        {
            #region
            /*
            // NorthwindEntities - 继承自 System.Data.Objects.ObjectContext
            // ObjectContext - 以对象（这些对象是 EDM 中定义的实体类型的实例）的形式与数据进行交互
            using (var ctx = new IQCDBEntities())
            {
                // CreateObjectName - 实体类 的 CreateObjectName 静态方法用于创建实体类的新实例
                // 构造函数的参数为对应的实体类的必填字段
                // 如果参数属于自增列，如本例中的 categoryID ，可以先对其赋予任意值
                var category = ParameterRange.CreateCategories(-1, txtCategoryName.Text);
                category.Description = txtDescription.Text;
                for (int i = 0; i < 10; i++)
                {
                    category.Products.Add(new Products() { ProductName = "测试用" + i.ToString() });
                }
                // AddToEntitySetName() - 将需要添加的对象添加到对象上下文中
                ctx.AddToCategories(category);
                // SaveChanges() - 将所有更新保存到相关存储区中
                ctx.SaveChanges();
                // SaveChanges() 之后就可以通过 category.CategoryID 来取得其自增列在数据库中所保存的值
                Page.ClientScript.RegisterStartupScript(this.GetType(), "js", "alert('CategoryID: " + category.CategoryID + "');", true);
            }
            */
            #endregion
            var pr = new ParameterRange();
            pr.partNo = txtpartNo.Text.Trim();
            pr.Parameter = txtParameter.Text.Trim();
            pr.Nominal = double.Parse(txtNominal.Text);
            pr.Max = double.Parse(txtMax.Text);
            pr.Min = double.Parse(txtMin.Text);
            new BaseRepositoryBLL<ParameterRange>().AddEntities(pr);


            GridView1.EditIndex = -1;
            BindData();
        }

        /// <summary>
        /// 根据partNo删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDel_Click(object sender, EventArgs e)
        {
            new BaseRepositoryBLL<ParameterRange>().DeleteEntities(p => p.partNo.Equals(txtpartNo.Text.Trim(), StringComparison.OrdinalIgnoreCase));
            QueryByPartNo();
        }

        /// <summary>
        /// 根据partNo查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            QueryByPartNo();
        }

        /// <summary>
        /// 根据partNo获取对象绑定到GV
        /// </summary>
        public void QueryByPartNo()
        {
            if (String.IsNullOrWhiteSpace(txtpartNo.Text))
                BindData();
            else
            {
                GridView1.DataSource = new BaseRepositoryBLL<ParameterRange>()
                    .LoadEntities(p => p.partNo.Equals(txtpartNo.Text.Trim(), 
                    StringComparison.OrdinalIgnoreCase)).ToList<ParameterRange>();
                GridView1.DataBind();
            }
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            /*
            using (var ctx = new IQCDBEntities())
            {
                var categoryId = (int)GridView1.DataKeys[e.RowIndex].Value;

                var category = ctx.Categories.First(p => p.CategoryID == categoryId);

                // 加载类别下的产品到当前上下文中，用以级联删除
                // 当然如果在数据库中配置了级联删除，并且映射中配置了<OnDelete Action="Cascade" />（EDM编辑器会根据数据库中的配置自动做此配置）则不用此句
                category.Products.Load();

                // DeleteObject() - 将指定的对象的状态更改为已删除（调用 SaveChanges() 之后才会执行）
                ctx.DeleteObject(category);

                ctx.SaveChanges();
            }*/
            var pr = new ParameterRange();
            pr.partNo = GridView1.DataKeys[e.RowIndex]["partNo"].ToString().Trim();
            pr.Parameter = GridView1.DataKeys[e.RowIndex]["Parameter"].ToString().Trim();
            new BaseRepositoryBLL<ParameterRange>().DeleteEntities(pr);
            GridView1.EditIndex = -1;
            BindData();
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            /*
            using (var ctx = new IQCDBEntities())
            {
                var categoryId = (int)GridView1.SelectedDataKey.Value;
                // 查找当前选中的类别下的产品集合
                var products = ctx.Products.Where(p => p.Categories.CategoryID == categoryId);
                // 将 System.Linq.IQueryable<Products> 绑定到 GridView2
                GridView2.DataSource = products;
                GridView2.DataBind();
            }*/
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            /*using (var ctx = new IQCDBEntities())
            {
                var categoryId = (int)GridView1.DataKeys[e.RowIndex].Value;
                var category = ctx.Categories.First(p => p.CategoryID == categoryId);
                // 修改 category 对象的属性
                category.CategoryName = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
                category.Description = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
                ctx.SaveChanges();
            }
            GridView1.EditIndex = -1;
            BindData();*/
            var pr = new ParameterRange();
            pr.partNo = GridView1.Rows[e.RowIndex].Cells[0].Text.Trim();
            pr.Parameter = GridView1.Rows[e.RowIndex].Cells[1].Text.Trim();
            pr.Nominal = double.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text.Trim());
            pr.Max = double.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.Trim());
            pr.Min = double.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text.Trim());
            new BaseRepositoryBLL<ParameterRange>().UpdateEntities(pr);
            //StandardDataBLL sd = new StandardDataBLL();
            //sd.UpdateParameterRange(pr);
            GridView1.EditIndex = -1;
            BindData();
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            BindData();
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            BindData();
        }

        public void Alert(string description)
        {
            if (description != null)
            {
                string scriptString = "<script language=JavaScript>";
                scriptString += "alert('" + description + "');";
                scriptString += " </script>";
                if (!Page.IsClientScriptBlockRegistered("clientScript"))
                    Page.RegisterClientScriptBlock("clientScript", scriptString);
            }
            else
            {
                Alert("描述信息为空！");
            }
        }

        protected void btnBatchImport_Click(object sender, EventArgs e)
        {
            if (FileUpload1.PostedFile.FileName == "" || FileUpload1.PostedFile.InputStream.Length < 1)
            {
                Alert("没有指定文件.");
            }
            else
            {
                try
                {
                    byte[] byFile = new byte[FileUpload1.PostedFile.ContentLength];
                    FileUpload1.PostedFile.InputStream.Read(byFile, 0, FileUpload1.PostedFile.ContentLength);
                    FileUpload1.PostedFile.InputStream.Close();
                    string strFile = System.Text.Encoding.ASCII.GetString(byFile);
                    string[] arrFile = strFile.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                    if (arrFile.Length == 0) return;
                   // IList<ParameterRange> listPR = new List<ParameterRange>();
                    foreach (string str in arrFile)
                    {
                        if (str.StartsWith("part", StringComparison.OrdinalIgnoreCase)) continue;
                        string[] sptmp = str.Split(',');
                        var pr = new ParameterRange();
                        pr.partNo = sptmp[0].Trim();
                        pr.Parameter = sptmp[1].Trim();
                        pr.Nominal = double.Parse(sptmp[2]);
                        pr.Max = double.Parse(sptmp[3]);
                        pr.Min = double.Parse(sptmp[4]);
                        new BaseRepositoryBLL<ParameterRange>().AddEntities(pr);
                    }
                   // StandardDataBLL sd = new StandardDataBLL();
                   // sd.SaveParameterRange(listPR);
                    GridView1.EditIndex = -1;
                    BindData();
                }
                catch (Exception err)
                {
                    Alert(err.Message);
                }
            }
        }


        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
        }

        protected void GridView1_PageIndexChanged(object sender, EventArgs e)
        {
            BindData();
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //判断是否数据行
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ((LinkButton)e.Row.Cells[5].Controls[2]).Attributes.Add("onclick",
                    string.Format("javascript:return confirm('您是要删除partNo为" + e.Row.Cells[0].Text +  "的标准吗？')"));
            }

            //if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
            //{
            //    ((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除：\"" + e.Row.Cells[1].Text + "\"吗?')");
            //}

        }

        

    }
}